<template>
  <a-spin :spinning="isLoading">
    <a-form layout="vertical" ref="formRef" :model="formData.data">
      <a-card size="small" :title="t('school-manage.title.paperSendInfo')">
        <a-row
          v-for="(sendItem, sendIndex) in formData.paperList"
          :key="sendIndex"
          :gutter="16"
          type="flex"
          justify="space-between"
          align="bottom"
          class="mb-15"
        >
          <a-col :span="4">
            <a-form-item
              :label="t('school-manage.label.receiver')"
              class="mb-0"
            >
              <a-input
                v-model:value="sendItem.schAddressee"
                :placeholder="placeHolder"
              />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item :label="t('school-manage.label.street')" class="mb-0">
              <a-input
                v-model:value="sendItem.schSendStreet"
                :placeholder="placeHolder"
              />
            </a-form-item>
          </a-col>
          <a-col :span="3">
            <a-form-item :label="t('school-manage.label.city')" class="mb-0">
              <a-input
                v-model:value="sendItem.schSendCity"
                :placeholder="placeHolder"
              />
            </a-form-item>
          </a-col>
          <a-col :span="3">
            <a-form-item
              :label="t('school-manage.label.province')"
              class="mb-0"
            >
              <a-input
                v-model:value="sendItem.schSendProvince"
                :placeholder="placeHolder"
              />
            </a-form-item>
          </a-col>
          <a-col :span="3">
            <a-form-item :label="t('school-manage.label.email')" class="mb-0">
              <a-input
                v-model:value="sendItem.schMailbox"
                :placeholder="placeHolder"
              />
            </a-form-item>
          </a-col>
          <a-col :span="3">
            <a-form-item :label="t('school-manage.label.school15')" class="mb-0">
              <a-select
                v-model:value="sendItem.schSendCountry"
                placeholder="请选择"
              >
                <a-select-option
                  v-for="item in dictLists.countryData"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="3">
            <a-form-item
              :label="t('school-manage.label.phone')"
              class="mb-0"
            >
              <a-input
                v-model:value="sendItem.schPhone"
                :placeholder="placeHolder"
                oninput="value=value.replace(/[^\d]/g,'')"
              />
            </a-form-item>
          </a-col>
          <a-col :span="1">
            <a-button
              v-if="sendIndex === 0"
              type="primary"
              ghost
              @click="addSendItem(2)"
              >{{ t("button.add") }}</a-button
            >
            <a-button
              v-else
              type="danger"
              ghost
              @click="deleteSendItem(sendIndex, 2)"
              >{{ t("button.delete") }}</a-button
            >
          </a-col>
        </a-row>
      </a-card>
      <a-card size="small" :title="t('school-manage.title.elcSendInfo')">
        <a-row
          v-for="(sendItem, sendIndex) in formData.electronList"
          :key="sendIndex"
          :gutter="16"
          type="flex"
          justify="flex-start"
          align="bottom"
          class="mb-15"
        >
          <a-col :span="5">
            <a-form-item
              :label="t('school-manage.label.receiver')"
              class="mb-0"
            >
              <a-input
                v-model:value="sendItem.schAddressee"
                :placeholder="placeHolder"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item :label="t('school-manage.label.school16')" class="mb-0">
              <a-input
                v-model:value="sendItem.schMailbox"
                :placeholder="placeHolder"
              />
            </a-form-item>
          </a-col>
          <a-col :span="1">
            <a-button
              v-if="sendIndex === 0"
              type="primary"
              ghost
              @click="addSendItem(1)"
              >{{ t("button.add") }}</a-button
            >
            <a-button
              v-else
              type="danger"
              ghost
              @click="deleteSendItem(sendIndex, 1)"
              >{{ t("button.delete") }}</a-button
            >
          </a-col>
        </a-row>
      </a-card>
      <a-card size="small" :title="t('school-manage.title.emailSuffix')">
        <a-form-item>
          <a-input
            v-model:value="formData.data.schMailboxSuffix"
            placeholder="请输入邮箱后缀；如有多个以；隔开"
          />
        </a-form-item>
      </a-card>
      <!-- <a-card size="small" :title="t('school-manage.title.overYearCalendar')">
        <a-row
          v-for="(calendarItem, calendarIndex) in formData.data
            .schCalendarYearList"
          :key="calendarIndex"
          :gutter="16"
          type="flex"
          justify="space-between"
          align="bottom"
          class="mb-15"
        >
          <a-col :span="5">
            <a-form-item :label="t('school-manage.label.term')" class="mb-0">
              <a-input
                v-model:value="calendarItem.schCySemester"
                :placeholder="placeHolder"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item
              :label="t('school-manage.label.beginTime')"
              class="mb-0"
            >
              <a-date-picker
                v-model:value="calendarItem.schCyBegindate"
                :placeholder="placeHolder"
                valueFormat="yyyy-MM-DD"
                type="date"
                class="w-100p"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item
              :label="t('school-manage.label.testTime')"
              class="mb-0"
            >
              <a-date-picker
                v-model:value="calendarItem.schCyExaminationdate"
                :placeholder="placeHolder"
                valueFormat="yyyy-MM-DD"
                type="date"
                class="w-100p"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item
              :label="t('school-manage.label.holidayTime')"
              class="mb-0"
            >
              <a-date-picker
                v-model:value="calendarItem.schHolidaydate"
                :placeholder="placeHolder"
                type="date"
                class="w-100p"
              />
            </a-form-item>
          </a-col>
          <a-col :span="1">
            <a-button
              v-if="calendarIndex === 0"
              type="primary"
              ghost
              @click="addCalendarItem(true)"
            >
              {{ t("button.add") }}
            </a-button>
            <a-button
              v-else
              type="danger"
              ghost
              @click="deleteCalendarItem(calendarIndex)"
            >
              {{ t("button.delete") }}
            </a-button>
          </a-col>
        </a-row>
      </a-card> -->
      <a-card size="small" :title="t('school-manage.title.attachmentInfo')">
        <a-form-item
          label="Logo"
          :rules="[{ required: false, message: '请选择Logo' }]"
        >
          <a-upload
            :showUploadList="false"
            :customRequest="data => handleUpload(data, 'logo')"
          >
            <a-button>{{ t("button.upload") }}</a-button>
            <p v-for="(item) in logoFiles" :key="item.fileId" class="mt-10">
              {{ item.name }}
              <DeleteOutlined
                class="ml-10 cursor-pointer"
                @click.prevent.stop="() => handleDelUpload('logo',item.fileId)"
              />
            </p>
          </a-upload>
        </a-form-item>
        <a-form-item :label="t('school-manage.label.pactDocument')">
          <a-upload
            :showUploadList="false"
            :customRequest="data => handleUpload(data, 'contract')"
          >
            <a-button>{{ t("button.upload") }}</a-button>
            <p v-for="item in contractFiles" :key="item.fileId" class="mt-10">
              {{ item.name }}
              <DeleteOutlined
                class="ml-10 cursor-pointer"
                @click.prevent.stop="() => handleDelUpload('contract',item.fileId)"
              />
            </p>
          </a-upload>
        </a-form-item>
        <a-form-item :label="t('school-manage.label.otherAttachment')">
          <a-upload
            :showUploadList="false"
            :customRequest="data => handleUpload(data, 'other')"
          >
            <a-button>{{ t("button.upload") }}</a-button>
            <p v-for="item in otherFiles" :key="item.fileId" class="mt-10">
              {{ item.name }}
              <DeleteOutlined
                class="ml-10 cursor-pointer"
                @click.prevent.stop="() => handleDelUpload('other',item.fileId)"
              />
            </p>
          </a-upload>
        </a-form-item>
        <a-form-item :label="t('school-manage.label.courseHeader')">
          <a-upload
            :showUploadList="false"
            :customRequest="data => handleUpload(data, 'courseHeader')"
          >
            <a-button>{{ t("button.upload") }}</a-button>
            <p
              v-for="item in courseHeaderFiles"
              :key="item.fileId"
              class="mt-10"
            >
              {{ item.name }}
              <DeleteOutlined
                class="ml-10 cursor-pointer"
                @click.prevent.stop="() => handleDelUpload('courseHeader',item.fileId)"
              />
            </p>
          </a-upload>
        </a-form-item>
        <a-form-item :label="t('school-manage.label.courseFooter')">
          <a-upload
            :showUploadList="false"
            :customRequest="data => handleUpload(data, 'courseFooter')"
          >
            <a-button>{{ t("button.upload") }}</a-button>
            <p
              v-for="item in courseFooterFiles"
              :key="item.fileId"
              class="mt-10"
            >
              {{ item.name }}
              <DeleteOutlined
                class="ml-10 cursor-pointer"
                @click.prevent.stop="() => handleDelUpload('courseFooter',item.fileId)"
              />
            </p>
          </a-upload>
        </a-form-item>
      </a-card>
    </a-form>
  </a-spin>
</template>

<script>
import { reactive, ref, computed, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import { upload } from "@/api/module/oss";
import { message } from "ant-design-vue";
import moment from 'moment'
import { getCountry } from '@/api/module/school'

export default {
  setup() {
    const { t } = useI18n();
    const placeHolder = "请输入";
    const isLoading = ref(false);
    const formRef = ref(null);
    const formData = reactive({
      data: {
        files: []
      },
      paperList: [],
      electronList: []
    });

    const logoFiles = computed(() =>
      formData.data.files.filter(v => v.type === "logo")
    );
    const contractFiles = computed(() =>
      formData.data.files.filter(v => v.type === "contract")
    );
    const otherFiles = computed(() =>
      formData.data.files.filter(v => v.type === "other")
    );
    const courseHeaderFiles = computed(() =>
      formData.data.files.filter(v => v.type === "courseHeader")
    );
    const courseFooterFiles = computed(() =>
      formData.data.files.filter(v => v.type === "courseFooter")
    );

    const schoolSendList = computed(() => {
      let arr = [...formData.paperList, ...formData.electronList]
      arr = arr.filter(obj => {
        let res = Object.keys(obj).some(key => {
          if (key == 'type') {
            return false
          } else {
            return obj[key]
          }
        })
        return res
      })
      return arr
    })

    const addSendItem = (type) => {
      if (type == 2) {
        formData.paperList.push({
          schAddressee: null,
          schPhone: null,
          schMailbox: null,
          schSendProvince: null,
          schSendCity: null,
          schSendStreet: null,
          schSendCountry: null,
          type: 2
        });
      } else if (type == 1) {
        formData.electronList.push({
          schAddressee: null,
          schPhone: null,
          schMailbox: null,
          schSendProvince: null,
          schSendCity: null,
          schSendStreet: null,
          schSendCountry: null,
          type: 1
        });
      } else {
        formData.paperList = [{
          schAddressee: null,
          schPhone: null,
          schMailbox: null,
          schSendProvince: null,
          schSendCity: null,
          schSendStreet: null,
          schSendCountry: null,
          type: 2
        }];
        formData.electronList = [{
          schAddressee: null,
          schPhone: null,
          schMailbox: null,
          schSendProvince: null,
          schSendCity: null,
          schSendStreet: null,
          schSendCountry: null,
          type: 1
        }];
      }
    };

    const deleteSendItem = (sendIndex, type) => {
      if (type == 1) {
        formData.electronList.splice(sendIndex, 1);
      } else {
        formData.paperList.splice(sendIndex, 1);
      }
    };

    // const addCalendarItem = (value) => {
    //   if (value) {
    //     formData.data.schCalendarYearList.push({
    //       schCySemester: "",
    //       schCyBegindate: "",
    //       schCyExaminationdate: "",
    //       schHolidaydate: ""
    //     });
    //   } else {
    //     formData.data.schCalendarYearList = [{
    //       schCySemester: "",
    //       schCyBegindate: "",
    //       schCyExaminationdate: "",
    //       schHolidaydate: ""
    //     }];
    //   }
    // };

    // const deleteCalendarItem = sendIndex => {
    //   console.log(sendIndex)
    //   formData.data.schCalendarYearList.splice(sendIndex, 1);
    // };

    const submit = () => {
      return new Promise(resolve => {
        formData.data.schoolSendList = schoolSendList.value
        formRef.value.validate().then(() => {
          resolve({ modelForm: formData.data });
        }).catch(err => {
          resolve({...err, modelForm: formData.data })
        });
      });
    };

    const handleUpload = (data, type) => {
      console.log(data,type)
      isLoading.value = true;
      const ajaxFormData = new FormData();
      ajaxFormData.append("file", data.file);
      upload(ajaxFormData).then(res => {
        if (res.code === 500) {
          message.error({ content: "上传图片失败" });
        } else {
          const { path: url, id: fileId, remark, name } = res.data;
          formData.data.files.push({ type, url, fileId, remark, name });
        }
        isLoading.value = false;
      }).finally(() => {
        isLoading.value = false;
      });
    };

    const handleDelUpload = (type,fileId) => {
      formData.data.files = formData.data.files.filter(v => {
          return v.fileId !== fileId
      });
    };

    const updateFormData = data => {
      // data.schCalendarYearList.length && data.schCalendarYearList.map(item => {
      //   item.schCyBegindate = item.schCyBegindate
      //                         ? moment(item.schCyBegindate).format('YYYY-MM-DD')
      //                         : ''
      //   item.schCyExaminationdate = item.schCyExaminationdate
      //                         ? moment(item.schCyExaminationdate).format('YYYY-MM-DD')
      //                         : ''
      //   item.schHolidaydate = item.schHolidaydate
      //                         ? moment(item.schHolidaydate).format('YYYY-MM-DD')
      //                         : ''
      // })
      formData.data = data;
      formData.paperList = []
      formData.electronList = []
      formData.data.schoolSendList.length === 0
              ? addSendItem()
              : formData.data.schoolSendList.forEach(i => {
                if (i.type == 1) {
                  formData.electronList.push(i)
                } else {
                  formData.paperList.push(i)
                }
              });
      formData.paperList.length === 0 && addSendItem(2)
      formData.electronList.length === 0 && addSendItem(1)
      // formData.data.schCalendarYearList.length === 0 && addCalendarItem();
    };
    const dictLists = reactive({
      data: {},
      countryData: []
    })
    onMounted(async () => {
      addSendItem();
      // addCalendarItem();
      const res = await getCountry({})
      dictLists.countryData = res.data.filter(item => item.parent == 0)
    });

    return {
      t,
      placeHolder,
      formRef,
      formData,
      isLoading,
      logoFiles,
      contractFiles,
      otherFiles,
      courseHeaderFiles,
      courseFooterFiles,
      addSendItem,
      deleteSendItem,
      // addCalendarItem,
      // deleteCalendarItem,
      submit,
      updateFormData,
      handleUpload,
      handleDelUpload,
      dictLists
    };
  }
};
</script>
